/*
 * This is the CD reader class that reads CD information from the file
 */
package edu.iyte.ceng431.hw03.cdplayer.controller;

import edu.iyte.ceng431.hw03.cdplayer.model.PlayingCD;
import edu.iyte.ceng431.hw03.cdplayer.model.Track;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
 *
 * @author hp
 */
public class CDReader {

    /*
     *Creates tracks from the information read from the CD file
     * and returns a new PlayingCD object including the tracks
     */
    public static PlayingCD readCDFile(String filePath) {
        PlayingCD cd = null;
        try {
            FileReader fr = new FileReader(filePath);
            String title = null, temp = "", trackTitle = null, artist = null, album = null;
            int year = 0, length = 0, order = 0;
            ArrayList<Track> tracks = new ArrayList<Track>();
            int ch;
            do {
                ch = fr.read();
                if (ch == '\r') {
                    if (title == null) {
                        title = temp;
                        temp = "";
                    } else {
                        try {
                            length = Integer.parseInt(temp);
                        } catch (NumberFormatException numberFormatException) {
                            length = 0;
                        }
                        order = 0;
                        temp = "";
                        tracks.add(new Track(trackTitle.substring(1, trackTitle.length()), artist, year, album, length));
                    }
                } else if (ch == 35) {
                    switch (order) {
                        case 0:
                            trackTitle = temp;
                            break;
                        case 1:
                            artist = temp;
                            break;
                        case 2:
                            try {
                                year = Integer.parseInt(temp);
                            } catch (NumberFormatException numberFormatException) {
                                year = 0;
                            }
                            break;
                        case 3:
                            album = temp;
                            break;
                    }
                    temp = "";
                    order++;
                } else {
                    temp += (char) ch;
                }

            } while (ch != -1);
            fr.close();
            cd = new PlayingCD(tracks, title);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.toString(),
                    "IO Error", JOptionPane.ERROR_MESSAGE);
            System.exit(-1);
        }
        return cd;
    }
}
